// @ts-nocheck
import axios from "axios" // 引入axios
import router from "@/router/index"
import * as util from "amtf/utils"

import { useUserStore } from "@/stores/use_user_store"
import { Notify, Dialog, Cookies } from "quasar"
import config from "@/api/api_config"
// console.log(`import.meta.env.VITE_BASE_API 👉`,import.meta.env.VITE_BASE_API)
// console.log(`process.env.API 👉`, process.env.API);
// console.log(`process.env 👉`, process.env);

const service = axios.create({
    baseURL: config.baseURL,
    // 下面这种方式quasar能自动代理?上面的却不行？
    // baseURL: process.env.API,
    timeout: 120000,
    withCredentials: false,
})

service.interceptors.request.use(
    config => {
        const userStore = useUserStore()
        config.headers = {
            "Content-Type": "application/json",
            "x-token": userStore.token,
            "x-user-id": userStore.userInfo.ID,
            ...config.headers,
        }
        return config
    },
    error => {
        Notify.create({
            type: "negative",
            message: error,
        })
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    response => {
        // console.log(`response.data 👉`, response.data)
        // console.log(`response.data?.data?.needInit 👉`, response.data?.data?.needInit)
        if (response.data?.data?.needInit) {
            router.push({ name: "Init" })
            return
        }
        const userStore = useUserStore()
        if (!response.config.donNotShowLoading) {
            // closeLoading()
        }
        if (response.headers["new-token"]) {
            userStore.setToken(response.headers["new-token"])
        }
        if (response.data.code === 0 || response.headers.success === "true") {
            if (response.headers.msg) {
                response.data.msg = decodeURI(response.headers.msg)
            }
            return response.data
        } else {
            console.log(`service.interceptors 出错 response  👉`, response)
            Notify.create({
                type: "negative",
                message: response.data.msg || decodeURI(response.headers.msg),
            })
            return response.data.msg ? response.data : response
        }
    },
    error => {
        if (!error.config.donNotShowLoading) {
            // closeLoading()
        }

        if (!error.response) {
            Dialog.create({
                title: "请求报错",
                message: `
              <p>检测到请求错误</p>
              <p>${error}</p>
              `,
                html: true,
                ok: {
                    label: "稍后重试",
                },
                cancel: {
                    label: "取消",
                },
            }).onOk(() => {
                // 这里可以添加稍后重试的逻辑，如果需要
            })
            return
        }

        switch (error.response.status) {
            case 500:
                Dialog.create({
                    title: "接口报错",
                    message: `
              <p>检测到接口错误${error}</p>
              <p>错误码<span style="color:red"> 500 </span>：此类错误内容常见于后台panic，请先查看后台日志，如果影响您正常使用可强制登出清理缓存</p>
              `,
                    html: true,
                    ok: {
                        label: "清理缓存",
                    },
                    cancel: {
                        label: "取消",
                    },
                }).onOk(() => {
                    const userStore = useUserStore()
                    userStore.ClearStorage()
                    router.push({ name: "Login", replace: true })
                })
                break
            case 404:
                console.log(`404 error 👉`, error)
                break
            case 401:
                Dialog.create({
                    title: "身份信息",
                    message: `
                <p>无效的令牌</p>
                <p>错误码:<span style="color:red"> 401 </span>错误信息:${error}</p>
                `,
                    html: true,
                    ok: {
                        label: "重新登录",
                    },
                    cancel: {
                        label: "取消",
                    },
                }).onOk(() => {
                    const userStore = useUserStore()
                    userStore.ClearStorage()
                    router.push({ name: "Login", replace: true })
                })
                break
        }

        return error
    }
)

export default service
